package com.menghao.rpc.spring;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * <p>全局Bean管理器.<br>
 *
 * @author MarvelCode.
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class BeansManager implements ApplicationContextAware {

    private static final BeansManager INSTANCE = new BeansManager();

    public static BeansManager getInstance() {
        return INSTANCE;
    }

    private ApplicationContext context;

    /**
     * ApplicationContextAware接口，用于注入Ioc上下文环境
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    public <T> T getBeanByType(Class<T> targetClass) {
        return context.getBean(targetClass);
    }

    public <T> T getBeanByType(String name, Class<T> targetClass) {
        return context.getBean(name, targetClass);
    }
}
